/**
 * PingCode API 服务类
 */

import type {
  WorkItem,
  Project,
  WorkItemType,
  WorkItemState,
  WorkItemPriority,
  User,
  ApiResponse,
  WorkItemQueryParams,
} from '../types/workItem';
import type {
  Workload,
  WorkloadType,
  WorkloadQueryParams,
} from '../types/workload';

export class PingCodeAPIService {
  private baseURL: string;
  private token: string;
  private useProxy: boolean;

  constructor() {
    // 从环境变量获取配置
    this.baseURL = process.env.NEXT_PUBLIC_PINGCODE_API_URL || 'https://yfxmgl.hainayun.net/open';
    this.token = process.env.NEXT_PUBLIC_PINGCODE_ACCESS_TOKEN || 'a48ae3d4-9b30-4523-9926-899507a77f55';
    // 在客户端环境中使用代理来避免CORS问题
    this.useProxy = typeof window !== 'undefined';
  }

  private async request<T>(endpoint: string, options: RequestInit = {}): Promise<T> {
    let url: string;
    let requestOptions: RequestInit;

    if (this.useProxy) {
      // 在客户端使用代理
      url = `/api/pingcode?path=${encodeURIComponent(endpoint)}`;
      requestOptions = {
        ...options,
        headers: {
          'Content-Type': 'application/json',
          ...options.headers,
        },
      };
    } else {
      // 在服务端直接调用
      url = `${this.baseURL}${endpoint}`;
      requestOptions = {
        ...options,
        headers: {
          'Authorization': `Bearer ${this.token}`,
          'Content-Type': 'application/json',
          ...options.headers,
        },
      };
    }

    // 添加调试日志
    console.log('API 请求:', {
      url,
      endpoint,
      useProxy: this.useProxy,
      baseURL: this.baseURL,
      token: this.token ? `${this.token.substring(0, 8)}...` : 'undefined',
      options: requestOptions
    });

    const response = await fetch(url, requestOptions);

    console.log('API 响应:', {
      status: response.status,
      statusText: response.statusText,
      ok: response.ok,
      headers: Object.fromEntries(response.headers.entries())
    });

    if (!response.ok) {
      const errorText = await response.text();
      console.error('API 错误详情:', errorText);
      throw new Error(`PingCode API 错误: ${response.status} ${response.statusText} - ${errorText}`);
    }

    const data = await response.json();
    console.log('API 返回数据:', data);
    return data;
  }

  // 获取项目列表
  async getProjects(params?: {
    name?: string;
    type?: string;
    page_index?: number;
    page_size?: number;
  }): Promise<ApiResponse<Project>> {
    const searchParams = new URLSearchParams();
    if (params) {
      Object.entries(params).forEach(([key, value]) => {
        if (value !== undefined) {
          searchParams.append(key, value.toString());
        }
      });
    }

    const endpoint = `/v1/project/projects${searchParams.toString() ? `?${searchParams.toString()}` : ''}`;
    return this.request<ApiResponse<Project>>(endpoint);
  }

  // 获取单个项目信息
  async getProject(projectId: string): Promise<Project> {
    return this.request<Project>(`/v1/project/projects/${projectId}`);
  }

  // 获取工作项列表
  async getWorkItems(params?: WorkItemQueryParams): Promise<ApiResponse<WorkItem>> {
    // 根据API文档，先尝试使用全局工作项接口
    // 如果不存在，则返回空结果并提示用户
    try {
      const searchParams = new URLSearchParams();

      // 设置默认参数
      const defaultParams = {
        page_size: 100, // 默认每页100条
        page_index: 1,  // 默认第一页
        ...params
      };

      if (defaultParams) {
        Object.entries(defaultParams).forEach(([key, value]) => {
          if (value !== undefined && value !== null && value !== '') {
            // 特别处理assignee_id参数，确保正确传递
            if (key === 'assignee_id' && typeof value === 'string') {
              searchParams.append('assignee_id', value);
            } else if (Array.isArray(value)) {
              value.forEach((v) => searchParams.append(key, v.toString()));
            } else {
              searchParams.append(key, value.toString());
            }
          }
        });
      }

      // 尝试使用全局工作项接口
      const endpoint = `/v1/project/work_items${searchParams.toString() ? `?${searchParams.toString()}` : ''}`;
      const response = await this.request<ApiResponse<WorkItem>>(endpoint);

      // 修复分页问题：如果请求的页面超出范围且总数大于0，自动调整到第一页
      if (response.values && response.values.length === 0 && response.total > 0 && defaultParams.page_index > 1) {
        console.log('检测到分页超出范围，自动调整到第一页');
        const adjustedParams = { ...defaultParams, page_index: 1 };
        const adjustedSearchParams = new URLSearchParams();

        Object.entries(adjustedParams).forEach(([key, value]) => {
          if (value !== undefined && value !== null && value !== '') {
            // 特别处理assignee_id参数，确保正确传递
            if (key === 'assignee_id' && typeof value === 'string') {
              adjustedSearchParams.append('assignee_id', value);
            } else if (Array.isArray(value)) {
              value.forEach((v) => adjustedSearchParams.append(key, v.toString()));
            } else {
              adjustedSearchParams.append(key, value.toString());
            }
          }
        });

        const adjustedEndpoint = `/v1/project/work_items${adjustedSearchParams.toString() ? `?${adjustedSearchParams.toString()}` : ''}`;
        return await this.request<ApiResponse<WorkItem>>(adjustedEndpoint);
      }

      return response;
    } catch (error) {
      console.warn('全局工作项接口不存在，返回空结果:', error);

      // 如果全局接口不存在，返回空结果
      // 并提示用户需要先选择项目
      return {
        page_size: 0,
        page_index: 0,
        total: 0,
        values: [],
        message: '请先选择一个项目来查看工作项'
      } as ApiResponse<WorkItem>;
    }
  }

  // 获取单个工作项详情
  async getWorkItem(workItemId: string): Promise<WorkItem> {
    return this.request<WorkItem>(`/v1/project/work_items/${workItemId}`);
  }

  // 获取工作项类型列表
  async getWorkItemTypes(projectId?: string): Promise<WorkItemType[]> {
    try {
      // 使用正确的API端点，不需要项目ID
      const response = await this.request<ApiResponse<WorkItemType>>('/v1/project/work_item_types');
      return response.values || [];
    } catch (error) {
      console.warn('获取工作项类型失败，使用默认类型:', error);
      return [
        { id: 'epic', name: '史诗' },
        { id: 'feature', name: '特性' },
        { id: 'story', name: '用户故事' },
        { id: 'task', name: '任务' },
        { id: 'bug', name: '缺陷' },
        { id: 'issue', name: '事务' },
      ];
    }
  }

  // 获取工作项状态列表
  async getWorkItemStates(projectId?: string): Promise<WorkItemState[]> {
    try {
      // 使用正确的API端点，不需要项目ID
      const response = await this.request<ApiResponse<WorkItemState>>('/v1/project/work_item_states');
      return response.values || [];
    } catch (error) {
      console.warn('获取工作项状态失败，使用默认状态:', error);
      return [
        { id: 'pending', name: '待处理', type: 'pending', color: '#ff7575' },
        { id: 'in_progress', name: '进行中', type: 'in_progress', color: '#F6C659' },
        { id: 'completed', name: '已完成', type: 'completed', color: '#5CB85C' },
      ];
    }
  }

  // 获取工作项优先级列表
  async getWorkItemPriorities(projectId?: string): Promise<WorkItemPriority[]> {
    // 如果没有项目ID，直接返回默认优先级
    if (!projectId) {
      console.log('没有项目ID，使用默认优先级');
      return [
        { id: 'highest', name: '最高' },
        { id: 'high', name: '高' },
        { id: 'medium', name: '中' },
        { id: 'low', name: '低' },
        { id: 'lowest', name: '最低' },
      ];
    }

    try {
      const endpoint = `/v1/project/work_item/priorities?project_id=${projectId}`;
      const response = await this.request<ApiResponse<WorkItemPriority>>(endpoint);
      return response.values || [];
    } catch (error) {
      console.warn('获取工作项优先级失败，使用默认优先级:', error);
      return [
        { id: 'highest', name: '最高' },
        { id: 'high', name: '高' },
        { id: 'medium', name: '中' },
        { id: 'low', name: '低' },
        { id: 'lowest', name: '最低' },
      ];
    }
  }

  // 获取用户列表
  async getUsers(params?: {
    name?: string;
    page_index?: number;
    page_size?: number;
  }): Promise<ApiResponse<User>> {
    const searchParams = new URLSearchParams();
    if (params) {
      Object.entries(params).forEach(([key, value]) => {
        if (value !== undefined) {
          searchParams.append(key, value.toString());
        }
      });
    }

    const endpoint = `/v1/directory/users${searchParams.toString() ? `?${searchParams.toString()}` : ''}`;
    return this.request<ApiResponse<User>>(endpoint);
  }

  // 获取项目成员列表
  async getProjectMembers(projectId: string, params?: {
    page_index?: number;
    page_size?: number;
  }): Promise<ApiResponse<{ id: string; type: string; user?: User; user_group?: any }>> {
    const searchParams = new URLSearchParams();
    if (params) {
      Object.entries(params).forEach(([key, value]) => {
        if (value !== undefined) {
          searchParams.append(key, value.toString());
        }
      });
    }

    const endpoint = `/v1/project/projects/${projectId}/members${searchParams.toString() ? `?${searchParams.toString()}` : ''}`;
    return this.request<ApiResponse<{ id: string; type: string; user?: User; user_group?: any }>>(endpoint);
  }

  // 创建工作项
  async createWorkItem(data: {
    project_id: string;
    type_id: string;
    title: string;
    description?: string;
    assignee_id?: string;
    priority_id?: string;
    state_id?: string;
    start_at?: number;
    end_at?: number;
    [key: string]: any;
  }): Promise<WorkItem> {
    return this.request<WorkItem>('/v1/project/work_items', {
      method: 'POST',
      body: JSON.stringify(data),
    });
  }

  // 更新工作项
  async updateWorkItem(workItemId: string, data: Partial<WorkItem>): Promise<WorkItem> {
    return this.request<WorkItem>(`/v1/project/work_items/${workItemId}`, {
      method: 'PATCH',
      body: JSON.stringify(data),
    });
  }

  // 删除工作项
  async deleteWorkItem(workItemId: string): Promise<WorkItem> {
    return this.request<WorkItem>(`/v1/project/work_items/${workItemId}`, {
      method: 'DELETE',
    });
  }

  // 创建项目
  async createProject(data: {
    name: string;
    identifier: string;
    type: string;
    description?: string;
    visibility?: 'private' | 'public';
    start_at?: number;
    end_at?: number;
    created_by?: string;
    created_by_id?: string;
    owner_id?: string;
    creator_id?: string;
    [key: string]: any;
  }): Promise<Project> {
    console.log('发送项目创建请求:', data);
    
    try {
      const result = await this.request<Project>('/v1/project/projects', {
        method: 'POST',
        body: JSON.stringify(data),
      });
      
      console.log('项目创建响应:', result);
      return result;
    } catch (error) {
      console.error('项目创建失败:', error);
      throw error;
    }
  }

  // 更新项目
  async updateProject(projectId: string, data: Partial<Project>): Promise<Project> {
    return this.request<Project>(`/v1/project/projects/${projectId}`, {
      method: 'PATCH',
      body: JSON.stringify(data),
    });
  }

  // 删除项目
  async deleteProject(projectId: string): Promise<Project> {
    return this.request<Project>(`/v1/project/projects/${projectId}`, {
      method: 'DELETE',
    });
  }

  // 查找用户（支持多种匹配方式）
  async findUserByName(name: string): Promise<User | null> {
    try {
      console.log(`正在查找用户: ${name}`);
      
      // 方法1: 精确匹配用户名
      let usersResponse = await this.getUsers({ name: name });
      let user = usersResponse.values?.find(u => 
        u.display_name === name || u.name === name
      );
      
      if (user) {
        console.log(`精确匹配找到用户:`, user);
        return user;
      }
      
      // 方法2: 模糊匹配 - 获取所有用户进行匹配
      usersResponse = await this.getUsers({ page_size: 100 });
      user = usersResponse.values?.find(u => 
        u.display_name?.includes(name) || 
        u.name?.includes(name) ||
        name.includes(u.display_name || '') ||
        name.includes(u.name || '')
      );
      
      if (user) {
        console.log(`模糊匹配找到用户:`, user);
        return user;
      }
      
      // 方法3: 尝试邮箱匹配（如果name包含@符号）
      if (name.includes('@')) {
        user = usersResponse.values?.find(u => u.email === name);
        if (user) {
          console.log(`邮箱匹配找到用户:`, user);
          return user;
        }
      }
      
      console.warn(`所有方法都未找到用户: ${name}`);
      console.log('可用用户列表:', usersResponse.values?.map(u => ({
        id: u.id,
        name: u.name,
        display_name: u.display_name,
        email: u.email
      })));
      
      return null;
    } catch (error) {
      console.error(`查找用户失败: ${name}`, error);
      return null;
    }
  }

  // 添加项目管理员
  async addProjectAdmins(projectId: string, adminNames: string[]): Promise<any> {
    console.log(`开始为项目 ${projectId} 添加管理员:`, adminNames);
    
    // 首先获取用户列表，根据姓名查找用户ID
    const userIds: string[] = [];
    const foundUsers: User[] = [];
    
    for (const adminName of adminNames) {
      const user = await this.findUserByName(adminName.trim());
      if (user) {
        userIds.push(user.id);
        foundUsers.push(user);
        console.log(`✅ 找到用户: ${adminName} -> ${user.display_name} (${user.id})`);
      } else {
        console.warn(`❌ 未找到用户: ${adminName}`);
      }
    }

    // 批量添加项目成员（管理员角色）
    if (userIds.length > 0) {
      try {
        // 尝试不同的API格式
        const requestBody = {
          members: userIds.map(userId => ({
            user_id: userId,
            role_id: 'admin' // 尝试使用 role_id 而不是 role
          }))
        };

        console.log('准备添加的管理员成员 (格式1):', requestBody);
        
        try {
          const result = await this.request(`/v1/project/projects/${projectId}/members`, {
            method: 'POST',
            body: JSON.stringify(requestBody),
          });
          
          console.log('✅ 成功添加管理员 (格式1):', foundUsers.map(u => u.display_name));
          return result;
        } catch (error1) {
          console.warn('格式1失败，尝试格式2:', error1);
          
          // 尝试第二种格式
          const requestBody2 = {
            user_ids: userIds,
            role: 'admin'
          };
          
          console.log('准备添加的管理员成员 (格式2):', requestBody2);
          
          try {
            const result = await this.request(`/v1/project/projects/${projectId}/members`, {
              method: 'POST',
              body: JSON.stringify(requestBody2),
            });
            
            console.log('✅ 成功添加管理员 (格式2):', foundUsers.map(u => u.display_name));
            return result;
          } catch (error2) {
            console.warn('格式2失败，尝试格式3:', error2);
            
            // 尝试第三种格式 - 逐个添加
            const results = [];
            for (const userId of userIds) {
              try {
                const requestBody3 = {
                  user_id: userId,
                  role: 'admin'
                };
                
                console.log('准备添加单个管理员 (格式3):', requestBody3);
                
                const result = await this.request(`/v1/project/projects/${projectId}/members`, {
                  method: 'POST',
                  body: JSON.stringify(requestBody3),
                });
                
                results.push(result);
                console.log(`✅ 成功添加单个管理员: ${foundUsers.find(u => u.id === userId)?.display_name}`);
              } catch (error3) {
                console.error(`❌ 添加单个管理员失败 (${userId}):`, error3);
              }
            }
            
            if (results.length > 0) {
              console.log('✅ 部分管理员添加成功');
              return results;
            } else {
              throw error2; // 抛出最后一个错误
            }
          }
        }
      } catch (error) {
        console.error('❌ 所有格式都失败，添加管理员失败:', error);
        throw error;
      }
    } else {
      console.warn('⚠️ 没有找到任何有效用户，跳过管理员添加');
      return null;
    }
  }

  // 移除项目成员
  async removeProjectMember(projectId: string, memberId: string): Promise<any> {
    return this.request(`/v1/project/projects/${projectId}/members/${memberId}`, {
      method: 'DELETE',
    });
  }

  // 获取工时列表
  async getWorkloads(params?: WorkloadQueryParams): Promise<ApiResponse<Workload>> {
    const searchParams = new URLSearchParams();

    // 设置默认参数
    const defaultParams = {
      page_size: 30, // 默认每页30条，与API文档一致
      page_index: 0,  // API使用0作为第一页
      ...params
    };

    console.log('工时查询API参数:', defaultParams);

    if (defaultParams) {
      Object.entries(defaultParams).forEach(([key, value]) => {
        if (value !== undefined && value !== null && value !== '') {
          searchParams.append(key, value.toString());
        }
      });
    }

    const endpoint = `/v1/workloads${searchParams.toString() ? `?${searchParams.toString()}` : ''}`;
    console.log('工时查询API端点:', endpoint);
    
    const response = await this.request<ApiResponse<Workload>>(endpoint);
    console.log('工时查询API响应:', {
      total: response.total,
      count: response.values?.length || 0,
      page_index: response.page_index,
      page_size: response.page_size
    });
    
    return response;
  }

  // 获取工时类型列表
  async getWorkloadTypes(): Promise<WorkloadType[]> {
    try {
      const response = await this.request<ApiResponse<WorkloadType>>('/v1/workload_types');
      return response.values || [];
    } catch (error) {
      console.warn('获取工时类型失败，使用默认类型:', error);
      return [
        { id: 'development', name: '研发' },
        { id: 'testing', name: '测试' },
        { id: 'design', name: '设计' },
        { id: 'management', name: '管理' },
        { id: 'other', name: '其他' },
      ];
    }
  }
}

// 单例实例
export const pingCodeAPI = new PingCodeAPIService();